import { input, select } from '@inquirer/prompts'
import path from 'path'
import fse from 'fs-extra'
import axios, { AxiosResponse } from 'axios'
import { gt } from 'lodash'
import { clone } from '../utils/clone'
import { name, version } from '../../package.json'
import log from '../utils/log'

interface ITemplateInfo {
  name: string
  downloadUrl: string
  description: string
  branch: string
}

const templateMap = new Map<string, ITemplateInfo>([
  ['vite-vue3-ts-back-template', {
    name: 'back-template',
    downloadUrl: 'git@gitee.com:apes-and-monkeys/vite-vue-typescript-back-template.git',
    description: '后台模板',
    branch: 'master'
  }],
  ['vite-create-vue-template', {
    name: 'common-template',
    downloadUrl: 'git@gitee.com:apes-and-monkeys/vite-create-vue-template.git',
    description: '普通vue3模板',
    branch: 'master'
  }],
  ['framework-project-demo', {
    name: 'framework-demo',
    downloadUrl: 'git@gitee.com:apes-and-monkeys/framework-project-demo.git',
    description: 'vue3框架proxy响应式系统',
    branch: 'master'
  }]
])

async function isOverwrite(dirname: string) {
  log.warn(`${dirname}文件夹存在`)
  return select({
    message: '是否覆盖？',
    choices: [
      { name: '覆盖', value: true },
      { name: '取消', value: false }
    ]
  })
}

async function getNPMLatestVersion(name: string) {
  try {
    const { data } = await axios.get(`https://registry.npmjs.org/${name}`) as AxiosResponse
    return data['dist-tags']['latest']
  } catch (error) {
    console.error(error)
  }
}

async function checkVersion(name: string, version: string) {
  const latestVersion = await getNPMLatestVersion(name)
  const need = gt(latestVersion, version)
  if (need) {
    log.warn(`检测到rysx的最新版本为：${latestVersion}，当前版本是${version}`)
    log.warn(`可以使用npm install rysx-cli@${latestVersion}，获得使用rysx update latest`)
  }
  return need
}

export async function createProject(projectName?: string) {
  const templateList = Array.from(templateMap).map(([name, info]: [string, ITemplateInfo]) => {
    return {
      name,
      value: name,
      description: info.description
    }
  })

  // 检测版本是否更新
  await checkVersion(name, version)

  if (!projectName) {
    projectName = await input({ message: '请输入项目名称' })
  }

  const filePath = path.resolve(process.cwd(), projectName)
  if (fse.existsSync(filePath)) {
    const run = await isOverwrite(projectName)
    if (!run) return
    fse.removeSync(filePath)
  }

  const templateName = await select({
    message: '请选择模板',
    choices: templateList
  })
  const info = templateMap.get(templateName)!
  if (templateName) {
    clone(info.downloadUrl, projectName, ['-b', info.branch])
  }
}